using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using Tryit.Models;

namespace Tryit.Views
{
    public partial class MaterialSelectionDialog : Window
    {
        public Dictionary<string, bool> SelectedMaterials { get; private set; }
        public Dictionary<string, double> TargetValues { get; private set; }

        private ObservableCollection<MaterialSelection> _materialSelections;
        private ObservableCollection<TargetValueSetting> _targetValueSettings;

        public ObservableCollection<MaterialSelection> MaterialSelections
        {
            get => _materialSelections;
            set
            {
                _materialSelections = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<TargetValueSetting> TargetValueSettings
        {
            get => _targetValueSettings;
            set
            {
                _targetValueSettings = value;
                OnPropertyChanged();
            }
        }

        public MaterialSelectionDialog(List<string> materialNames, List<ElementComposition> outOfRangeElements)
        {
            InitializeComponent();
            
            // 初始化材料选择列表
            MaterialSelections = new ObservableCollection<MaterialSelection>();
            foreach (var materialName in materialNames)
            {
                MaterialSelections.Add(new MaterialSelection { MaterialName = materialName, IsSelected = false });
            }

            // 初始化目标值设置列表
            TargetValueSettings = new ObservableCollection<TargetValueSetting>();
            foreach (var element in outOfRangeElements)
            {
                // 默认目标值设为内控要求的中间值
                var targetValue = GetDefaultTargetValue(element);
                TargetValueSettings.Add(new TargetValueSetting 
                { 
                    ElementName = element.Name, 
                    TargetValue = targetValue 
                });
            }

            DataContext = this;
        }

        private double GetDefaultTargetValue(ElementComposition element)
        {
            if (string.IsNullOrEmpty(element.InternalRequirement))
                return element.ActualValue;

            try
            {
                var range = ParseRange(element.InternalRequirement);
                return (range.min + range.max) / 2.0;
            }
            catch
            {
                return element.ActualValue;
            }
        }

        private (double min, double max) ParseRange(string range)
        {
            if (string.IsNullOrEmpty(range)) return (0, 0);

            range = range.Replace(" ", "");

            if (range.Contains("~"))
            {
                var parts = range.Split('~', StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length == 2)
                {
                    if (double.TryParse(parts[0], out double min) && double.TryParse(parts[1], out double max))
                    {
                        if (min > max)
                        {
                            (min, max) = (max, min);
                        }
                        return (min, max);
                    }
                }
            }
            else if (range.Contains("≤"))
            {
                if (double.TryParse(range.Replace("≤", ""), out double value))
                {
                    return (double.MinValue, value);
                }
            }
            else if (range.Contains("≥"))
            {
                if (double.TryParse(range.Replace("≥", ""), out double value))
                {
                    return (value, double.MaxValue);
                }
            }
            else if (range.Contains("＜"))
            {
                if (double.TryParse(range.Replace("＜", ""), out double value))
                {
                    return (double.MinValue, value);
                }
            }
            else if (range.Contains("＞"))
            {
                if (double.TryParse(range.Replace("＞", ""), out double value))
                {
                    return (value, double.MaxValue);
                }
            }
            else
            {
                if (double.TryParse(range, out double value))
                {
                    return (value, value);
                }
            }

            return (0, 0);
        }

        private void ConfirmButton_Click(object sender, RoutedEventArgs e)
        {
            // 收集选中的材料
            SelectedMaterials = MaterialSelections
                .ToDictionary(ms => ms.MaterialName, ms => ms.IsSelected);

            // 收集目标值
            TargetValues = TargetValueSettings
                .ToDictionary(tvs => tvs.ElementName, tvs => tvs.TargetValue);

            DialogResult = true;
            Close();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class MaterialSelection : INotifyPropertyChanged
    {
        private string _materialName = "";
        private bool _isSelected;

        public string MaterialName
        {
            get => _materialName;
            set
            {
                _materialName = value;
                OnPropertyChanged();
            }
        }

        public bool IsSelected
        {
            get => _isSelected;
            set
            {
                _isSelected = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class TargetValueSetting : INotifyPropertyChanged
    {
        private string _elementName = "";
        private double _targetValue;

        public string ElementName
        {
            get => _elementName;
            set
            {
                _elementName = value;
                OnPropertyChanged();
            }
        }

        public double TargetValue
        {
            get => _targetValue;
            set
            {
                _targetValue = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
} 